package com.tiantang.study.netty.reactor;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author liujinkun
 * @Title: Dispatcher
 * @Description: reactor模型中的Dispatcher类，负责event事件的转发和EventHandler的维护
 * @date 2019/5/5 11:04 PM
 */
public class Dispatcher {

    // 通过ConcurrentHashMap来维护不同类型的事件处理器
    private Map<EventType,EventHandler> eventHandlerMap = new ConcurrentHashMap<EventType, EventHandler>();

    private Selector selector;

    public Dispatcher(Selector selector){
        this.selector = selector;
    }

    public void registerEventHandler(EventType eventType,EventHandler eventHandler){
        this.eventHandlerMap.put(eventType,eventHandler);
    }

    public void removeEventHandler(EventType eventType){
        this.eventHandlerMap.remove(eventType);
    }

    public void handleEvents(){
        dispatch();
    }

    /**
     * 简单实现事件的分发功能，此处中的处理器全部采用同步操作，在reactor模式的典型实现NIO中都是采用handle异步处理，来保证非阻塞
     */
    public void dispatch(){
        while(true){
            List<Event> events = selector.select();
            for (Event event : events) {
                EventHandler eventHandler = eventHandlerMap.get(event.getEventType());
                eventHandler.handle(event);
            }
        }
    }

}
